package cn.com.acca.ma.common.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化和反序列化工具类
 */
public class SerializableUtil {
    /**
     * 对象转数组
     *
     * @param obj
     * @return
     */
    public synchronized static byte[] toByteArray(Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return bytes;
    }

    /**
     * 数组转对象
     *
     * @param bytes
     * @return
     */
    public synchronized static Object toObject(byte[] bytes) {
        Object obj = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            obj = ois.readObject();
            ois.close();
            bis.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return obj;
    }

//    public static <T> byte[] toByteArray(T t) {
//        Schema schema = RuntimeSchema.getSchema(t.getClass());
//        return ProtobufIOUtil.toByteArray(t, schema,
//                LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
//
//    }
//
//
//    public static <T> T toObject(byte[] bytes, Class<T> c) {
//        T t = null;
//        try {
//            t = c.newInstance();
//            Schema schema = RuntimeSchema.getSchema(t.getClass());
//            System.out.println(new String(bytes, "utf-8"));
//            System.out.println(t.getClass());
//            System.out.println(schema.messageFullName());
//            ProtobufIOUtil.mergeFrom(bytes, t, schema);
//        } catch (InstantiationException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        return t;
//    }
}
